package com.vnp.vchat.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vnp.vchat.ChatActivity;
import com.vnp.vchat.MainActivity;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.R.layout;
import com.vnp.vchat.Util.Common;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.adapter.SearchAdapter;
import com.vnp.vchat.bean.ObjContact;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.database.DBAdapter;
import com.vnp.vchat.database.DBFunction;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.version2.ChatNewActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DanhbaScr extends Fragment {

	TextView title;
	ListView listContact;
	PreferenceHelper preferenceHelper;
	String hash;
	
	SearchAdapter adapter;
	
	ArrayList<ObjKhachhang> objKhachhangs = new ArrayList<ObjKhachhang>();
	
	int page = 0;
	
	RelativeLayout llProgressBar;
	TextView txtNoContact;
	ProgressBar progressBar;
	
	private int preLast;
	boolean isLoading = false;
	Handler mHandler = new Handler();
	
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			getDanhba(++page);
		}
	};
	
	DBFunction dbFunction;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		dbFunction = new DBFunction(DBAdapter.getObj(getActivity()));
		dbFunction.getContactSV();
		preferenceHelper = new PreferenceHelper(getActivity());
		hash = Utils.MD5(Common.KEY_HTTP+"|"+preferenceHelper.getUserId());
	}
	
	ViewGroup viewGroup;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if(viewGroup==null) {
			viewGroup = (ViewGroup) inflater.inflate(R.layout.scr_danhba, container, false);
		} else {
			((ViewGroup) viewGroup.getParent()).removeView(viewGroup);
		}
		title = (TextView) viewGroup.findViewById(R.id.title);
		listContact = (ListView) viewGroup.findViewById(R.id.list_contact);
		txtNoContact = (TextView) viewGroup.findViewById(R.id.txt_no_contact);
		progressBar = (ProgressBar) viewGroup.findViewById(R.id.progressBar1);
		
		llProgressBar = (RelativeLayout) viewGroup.findViewById(R.id.ll_progress_bar);
		
		
		objKhachhangs.addAll(dbFunction.getContactSV());
		adapter = new SearchAdapter(getActivity(), objKhachhangs);
		listContact.setAdapter(adapter);
		
		init();
		setFont();
		
		getDanhba(page);
		
		listContact.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastItem  = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount){
					if (preLast != lastItem) {
						int last_pos = listContact.getLastVisiblePosition();
						if (last_pos >= objKhachhangs.size()-1){
							llProgressBar.setVisibility(View.VISIBLE);
							mHandler.removeCallbacks(r);
							mHandler.postDelayed(r, 500);
						}
						preLast = lastItem;
					}
					
				}
			}
		});
		
		listContact.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				MainPanelActivity.onGoto = true;
				Intent c = new Intent(getActivity(),ChatNewActivity.class);
				c.putExtra("khachhang", objKhachhangs.get(position));
				startActivity(c);
				getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
			}
			
		});
		return viewGroup;
	}
	
	
	void init(){
		title.setText("Danh bạ");
	}
	
	void setFont(){
		title.setTypeface(Utils.getTypefaceBold(getActivity()));
	}
	
	void getDanhba(int page){
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				progressBar.setVisibility(View.GONE);
				llProgressBar.setVisibility(View.GONE);
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					progressBar.setVisibility(View.GONE);
					llProgressBar.setVisibility(View.GONE);
					if (status == 1){
						JSONArray ja = re.getJSONArray("data");
						
						Log.i("DATA", "DANH BA: "+ja.toString());
						
						if (ja.length() > 0){
							for (int i = 0; i < ja.length(); i++) {
								JSONObject jo = ja.getJSONObject(i);
								
								int id = jo.getInt("id");
								String name = jo.getString("name");
								String avatar = jo.getString("avatar");
								String contact = jo.getString("contact");
//								String from = jo.getString("from");
								
								ObjKhachhang objKhachhang = new ObjKhachhang();
								objKhachhang.setId(String.valueOf(id));
								objKhachhang.setName(name);
								objKhachhang.setUrlAvatar(avatar);
								objKhachhang.setLoginName(contact);
								objKhachhang.setUrlDangxem("");
								
								objKhachhangs.add(objKhachhang);
								
								dbFunction.updateContactSV(objKhachhang);
							}
						} else {
							txtNoContact.setVisibility(View.VISIBLE);
						}
						objKhachhangs.clear();
						objKhachhangs.addAll(dbFunction.getContactSV());
						adapter.notifyDataSetChanged();
					} else {
					}
					
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			
		});
		httpClientHelper.getContact(preferenceHelper.getAdminId(), preferenceHelper.getHashSetting(), page);
	}
	
	
}
